import axios from 'axios'

import store from '@/store'

import { API_HOST, API_TIME_OUT } from '@/config/http'

const http = axios.create({
	baseURL: API_HOST,
	timeout: API_TIME_OUT
})

/* 请求拦截 */
http.interceptors.request.use(config => {
	config.headers['Authori-zation'] = `Bearer ${store.state.user.token}`
    return config
}, error => {
  return Promise.reject(error)
})

/* 响应拦截 */
http.interceptors.response.use(response => {
  return response.data
}, error => {
  return error
})

axios.defaults.adapter = function(config) { //自己定义个适配器，用来适配uniapp的语法
    return new Promise((resolve, reject) => {
        const settle = require('axios/lib/core/settle');
        const buildURL = require('axios/lib/helpers/buildURL');
        uni.request({
            method: config.method.toUpperCase(),
            url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
            header: config.headers,
            data: config.data,
            dataType: config.dataType,
            responseType: config.responseType,
            sslVerify: config.sslVerify,
            complete: function complete(response) {
                response = {
                    data: response.data,
                    status: response.statusCode,
                    errMsg: response.errMsg,
                    header: response.header,
                    config: config
                };

                settle(resolve, reject, response);
            }
        })
    })
}

export default http
